package cn.duli.xianer.service.impl;

import cn.duli.xianer.service.FileService;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class FileServiceImpl implements FileService {


    @Autowired
    private UploadManager uploadManager;

    @Autowired
    FileService fileService;

    @Value("${baseUploadUrl}")
    private String url;

    @Value("${qiniu.path}")
    private String path;

    @Autowired
    private Auth auth;


    @Value("${qiniu.bucket}")
    private String bucket;


    private StringMap putPolicy;

    @Override
    public Map uploadFile(File file) throws QiniuException {
        Map map = new HashMap();
        Response response = this.uploadManager.put(file,null,getUploadToken());
        //解析上传的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);

        String imageName = putRet.hash;
        int retry = 0;
        while(response.needRetry() && retry < 3){
            response = this.uploadManager.put(file,null,getUploadToken());
        }
        map.put("response",response);
        map.put("imgName",imageName);
        return map;
    }

    @Override
    public String uploadOneFile(MultipartFile upFile) {
        String fileName = upFile.getOriginalFilename();
        File file = new File(url + fileName);
        try {
            // 将MulitpartFile文件转化为file文件格式
            upFile.transferTo(file);
            // 将图片上传到七牛云服务器，获取到图片地址
            Map response = fileService.uploadFile(file);
            Object imageName = response.get("imgName");
            // 图片地址
            String imgUrl = path + "/" + imageName;
            return imgUrl;

        } catch (Exception e) {
            e.printStackTrace();
            return "upload false";
        }
    }


    private String getUploadToken(){
        return this.auth.uploadToken(bucket,null,3600,putPolicy);
    }



}

